package com.woniu.goods.realms;

import com.woniu.goods.entity.User;
import com.woniu.goods.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token= (UsernamePasswordToken) authenticationToken;

        String username=token.getUsername();
        User user=userService.queryUserByName(username);

        if (user==null){
            throw new UnknownAccountException("账号不存在");
        }

        ByteSource byteSource =ByteSource.Util.bytes(username);
        SimpleAuthenticationInfo info=
                    new SimpleAuthenticationInfo(user,user.getPassword(),byteSource,this.getName());
        SecurityUtils.getSubject().getSession().setAttribute("userid",user.getUserid());
        return info;
    }

    public static void main(String[] args) {
       Object o=new SimpleHash("MD5","123","admin",128);
        System.out.println(o.toString());
    }
}
